<!--
 * @Author: Mr · Lei
 * @Date: 2024-10-17 10:57:29
 * @LastEditors: OBKoro1
 * @LastEditTime: 2024-10-17 10:57:29
 * @FilePath: \ruituan-tuan-web\src\views\nfc\nfc-config\index.vue
 * @Description: 
 * 
 * Copyright (c) 2024 by 四川开局红科技有限公司, All Rights Reserved. 
-->
<template>
  <div class="container">
    <Breadcrumb :items="['menu.nfc','menu.nfc.log']" />
    <a-card class="general-card" :title="$t('incomeLog.title')">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 5 }"
            :wrapper-col-props="{ span: 16 }"
            label-align="left"
          >
            <a-row :gutter="16">
              <!-- 客户昵称搜索 -->
              <a-col :span="6">
                <a-form-item
                  field="user.nickname"
                  :label="$t('incomeLog.form.nickname')"
                >
                  <a-input
                    v-model="formModel['user.nickname']"
                    :placeholder="$t('incomeLog.form.placeholder.nickname')"
                  />
                </a-form-item>
              </a-col>
              <!-- 客户电话搜索 -->
              <a-col :span="6">
                <a-form-item
                  field="user.moblie"
                  :label="$t('incomeLog.form.mobile')"
                >
                  <a-input
                    v-model="formModel['user.mobile']"
                    :placeholder="$t('incomeLog.form.placeholder.mobile')"
                  />
                </a-form-item>
              </a-col>
              <!-- 订单号 -->

              <a-col :span="6">
                <a-form-item
                  field="shop.name"
                  :label="$t('incomeLog.form.shop.name')"
                >
                  <a-input
                    v-model="formModel['shop.name']"
                    :placeholder="$t('incomeLog.form.placeholder.shop.name')"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item
                  field="orderinfo.order_no"
                  :label="$t('incomeLog.form.order_no')"
                >
                  <a-input
                    v-model="formModel['orderinfo.order_no']"
                    :placeholder="$t('incomeLog.form.placeholder.order_no')"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="6">
                <a-form-item field="rate" :label="$t('incomeLog.form.rate')">
                  <a-input
                    v-model="formModel['rate']"
                    :placeholder="$t('incomeLog.form.placeholder.rate')"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item
                  field="createtime"
                  :label="$t('incomeLog.form.createtime')"
                >
                  <a-range-picker @change="changeDate" @clear="clearDate" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              {{ $t('incomeLog.form.search') }}
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              {{ $t('incomeLog.form.reset') }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            {{ $t('incomeLog.table.title') }}
          </a-space>
        </a-col>
        <a-col
          :span="12"
          style="display: flex; align-items: center; justify-content: end"
        >
          <a-tooltip :content="$t('incomeLog.actions.refresh')">
            <div class="action-icon" @click="search"
              ><icon-refresh size="18"
            /></div>
          </a-tooltip>
          <a-dropdown @select="handleSelectDensity">
            <a-tooltip :content="$t('incomeLog.actions.density')">
              <div class="action-icon"><icon-line-height size="18" /></div>
            </a-tooltip>
            <template #content>
              <a-doption
                v-for="item in densityList"
                :key="item.value"
                :value="item.value"
                :class="{ active: item.value === size }"
              >
                <span>{{ item.name }}</span>
              </a-doption>
            </template>
          </a-dropdown>
          <a-tooltip :content="$t('incomeLog.actions.columnSetting')">
            <a-popover
              trigger="click"
              position="bl"
              @popup-visible-change="popupVisibleChange"
            >
              <div class="action-icon"><icon-settings size="18" /></div>
              <template #content>
                <div id="tableSetting">
                  <div
                    v-for="(item, index) in showColumns"
                    :key="item.dataIndex"
                    class="setting"
                  >
                    <div style="margin-right: 4px; cursor: move">
                      <icon-drag-arrow />
                    </div>
                    <div>
                      <a-checkbox
                        v-model="item.checked"
                        @change="
                          handleChange($event, item as TableColumnData, index)
                        "
                      >
                      </a-checkbox>
                    </div>
                    <div class="title">
                      {{ item.title === '#' ? '序列号' : item.title }}
                    </div>
                  </div>
                </div>
              </template>
            </a-popover>
          </a-tooltip>
        </a-col>
      </a-row>
      <a-table
        row-key="id"
        column-resizable
        :loading="loading"
        :pagination="pagination"
        :columns="(cloneColumns as TableColumnData[])"
        :data="renderData"
        :bordered="{ wrapper: true, cell: true }"
        :size="size"
        @page-change="onPageChange"
      >
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 + (pagination.page - 1) * pagination.limit }}
        </template>
        <template #logo="{ record }">
          <a-image width="50" height="50" :src="record.shop.logo" />
        </template>
        <template #avatar="{ record }">
          <a-image width="50" height="50" :src="record.user.avatar" />
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive, watch, nextTick } from 'vue';
  import { useI18n } from 'vue-i18n';
  import useLoading from '@/hooks/loading';
  import { GetIncomeLogListApi, PolicyRecord, PolicyParams } from '@/api/nfc';
  import { Pagination } from '@/types/global';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import cloneDeep from 'lodash/cloneDeep';
  import Sortable from 'sortablejs';

  type SizeProps = 'mini' | 'small' | 'medium' | 'large';
  type Column = TableColumnData & { checked?: true };

  const generateFormModel = () => {
    return {
      'rate': '',
      'orderinfo.order_no': '',
      'shop.name': '',
      'shop.address': '',
      'user.nickname': '',
      'user.mobile': '',
      'createtime': '',
    };
  };
  const generateFormModelOp = () => {
    return {
      'rate': '=',
      'orderinfo.order_no': '=',
      'shop.name': 'like',
      'user.nickname': 'like',
      'user.mobile': 'like',
      'createtime': 'BETWEEN',
    };
  };
  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const renderData = ref<PolicyRecord[]>([]);
  const formModel = ref(generateFormModel());
  const formModelOp = ref(generateFormModelOp());

  const cloneColumns = ref<Column[]>([]);
  const showColumns = ref<Column[]>([]);

  const size = ref<SizeProps>('medium');

  // 分页属性
  const basePagination: Pagination = {
    page: 1,
    limit: 10,
  };
  const pagination = reactive({
    ...basePagination,
  });
  // 定义尺寸
  const densityList = computed(() => [
    {
      name: t('incomeLog.size.mini'),
      value: 'mini',
    },
    {
      name: t('incomeLog.size.small'),
      value: 'small',
    },
    {
      name: t('incomeLog.size.medium'),
      value: 'medium',
    },
    {
      name: t('incomeLog.size.large'),
      value: 'large',
    },
  ]);
  // 查询结果 每列标题与字段
  const columns = computed<TableColumnData[]>(() => [
    {
      title: t('incomeLog.columns.index'),
      dataIndex: 'index',
      slotName: 'index',
      align: 'center',
    },
    {
      title: t('incomeLog.columns.orderinfo.order_no'),
      dataIndex: 'orderinfo.order_no',
      align: 'center',
    },
    {
      title: t('incomeLog.columns.shop.name'),
      dataIndex: 'shop.name',
      align: 'center',
    },
    {
      title: t('incomeLog.columns.shop.logo'),
      dataIndex: 'shop.logo',
      slotName: 'logo',
      align: 'center',
    },
    {
      title: t('incomeLog.columns.user.avatar'),
      dataIndex: 'avatar',
      slotName: 'avatar',
      align: 'center',
    },
    {
      title: t('incomeLog.columns.user.nickname'),
      dataIndex: 'user.nickname',
      align: 'center',
    },
    {
      title: t('incomeLog.columns.user.mobile'),
      dataIndex: 'user.mobile',
      align: 'center',
    },
    {
      title: t('incomeLog.columns.money'),
      dataIndex: 'money',
      align: 'center',
    },
    {
      title: t('incomeLog.columns.order_profit'),
      dataIndex: 'order_profit',
      align: 'center',
    },
    
    {
      title: t('incomeLog.columns.rate'),
      dataIndex: 'rate',
      align: 'center',
    },
    {
      title: t('incomeLog.columns.createtime'),
      dataIndex: 'createtime',
      align: 'center',
    },
  ]);

  // 查询/筛选 列表
  const fetchData = async (params: PolicyParams = { page: 1, limit: 10 }) => {
    setLoading(true);
    try {
      const { data } = await GetIncomeLogListApi(params);
      renderData.value = data.data;
      pagination.page = params.page;
      pagination.total = data.total;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };
  // 转换选择的日期为时间戳
  const changeDate = (even: any) => {
    const starDate = (new Date(even[0]).getTime() / 1000).toString();
    const endDate = (new Date(even[1]).getTime() / 1000).toString();

    formModel.value.createtime = `${starDate},${endDate}`;
  };

  const search = () => {
    fetchData({
      ...basePagination,
      filter: JSON.stringify(formModel.value),
      op: JSON.stringify(formModelOp.value),
    } as unknown as PolicyParams);
  };
  search();

  const onPageChange = (page: number) => {
    basePagination.page = page;
    search();
  };
  // 清除选择的日期
  const clearDate = () => {
    basePagination.page = 1;
    search();
  };
  const reset = () => {
    formModel.value = generateFormModel();
    basePagination.page = 1;
    search();
  };

  const handleSelectDensity = (
    val: string | number | Record<string, any> | undefined,
    e: Event
  ) => {
    size.value = val as SizeProps;
  };

  const handleChange = (
    checked: boolean | (string | boolean | number)[],
    column: Column,
    index: number
  ) => {
    if (!checked) {
      cloneColumns.value = showColumns.value.filter(
        (item) => item.dataIndex !== column.dataIndex
      );
    } else {
      cloneColumns.value.splice(index, 0, column);
    }
  };

  const exchangeArray = <T extends Array<any>>(
    array: T,
    beforeIdx: number,
    newIdx: number,
    isDeep = false
  ): T => {
    const newArray = isDeep ? cloneDeep(array) : array;
    if (beforeIdx > -1 && newIdx > -1) {
      // 先替换后面的，然后拿到替换的结果替换前面的
      newArray.splice(
        beforeIdx,
        1,
        newArray.splice(newIdx, 1, newArray[beforeIdx]).pop()
      );
    }
    return newArray;
  };

  const popupVisibleChange = (val: boolean) => {
    if (val) {
      nextTick(() => {
        const el = document.getElementById('tableSetting') as HTMLElement;
        const sortable = new Sortable(el, {
          onEnd(e: any) {
            const { oldIndex, newIndex } = e;
            exchangeArray(cloneColumns.value, oldIndex, newIndex);
            exchangeArray(showColumns.value, oldIndex, newIndex);
          },
        });
      });
    }
  };

  watch(
    () => columns.value,
    (val) => {
      cloneColumns.value = cloneDeep(val);
      cloneColumns.value.forEach((item, index) => {
        item.checked = true;
      });
      showColumns.value = cloneDeep(cloneColumns.value);
    },
    { deep: true, immediate: true }
  );
</script>

<script lang="ts">
  export default {
    name: 'List',
  };
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }

  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }

  .action-icon {
    margin-left: 12px;
    cursor: pointer;
  }

  .active {
    color: #0960bd;
    background-color: #e3f4fc;
  }

  .setting {
    display: flex;
    align-items: center;
    width: 200px;

    .title {
      margin-left: 12px;
      cursor: pointer;
    }
  }
</style>
